package com.bwie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.config.MyNacosConfig;
import com.bwie.mapper.TbUserMapper;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.utils.R;
import com.bwie.vo.LoginVo;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description :
 * @Author QiHainan
 * @Create 2025/3/21 18:15
 * @Version 1.0
 */
@RestController
@RequestMapping("/user/index")
@RefreshScope
public class IndexController {

    @Autowired
    private TbUserService tbUserService;
    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    MyNacosConfig myNacosConfig;

    @Value("${site.className}")
    private String className;

    @PostMapping("/getUserById/{userId}")
    public R getUserById(@PathVariable(name = "userId") int userId){
        return tbUserService.getUserById(userId);
    }

    /**
     * 管理员登录
     * @param loginVo
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo){
        //判断用户是否存在
        TbUser tbUser = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserName,loginVo.getUserName())
        );
        if(tbUser == null){
            return R.ERROR(404,"用户不存在");
        }
        //密码是否正确
        if(!tbUser.getUserPass().equals(loginVo.getUserPass())){
            return R.ERROR(500,"密码错误");
        }
        //生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("useName", tbUser.getUserName())
                .claim("realName", tbUser.getRealName())
                .compact();
        //缓存token
        String tokenKey = "token-" + tbUser.getUserId();
        redisTemplate.opsForValue().set(tokenKey,token,60, TimeUnit.MINUTES);
        //返回用户信息
        tbUser.setUserPass(null);
        tbUser.setToken(token);
        return R.OK(tbUser);
    }

    /**
     * 分页获取商户
     * @param pageInfoVo
     * @return
     */
    @PostMapping("/getUserList")
    public R getUserList(@RequestBody PageInfoVo pageInfoVo){
        return tbUserService.getUserList(pageInfoVo);
    }

    /**
     * 商户注册
     * @return
     */
    @PostMapping("/addUser")
    public R addUser(@RequestBody @Validated TbUser tbUser, BindingResult result){
        if(result.hasErrors()){
            return R.ERROR(500,result.getAllErrors().toString());
        }
        return tbUserService.addUser(tbUser);
    }

    /**
     * 编辑商户信息
     * @param tbUser
     * @return
     */
    @PostMapping("/updateUser")
    public R updateUser(@RequestBody TbUser tbUser){
        return tbUserService.updateUser(tbUser);
    }

    /**
     * 从nacos配置中心读取配置数据
     * @return
     */
    @PostMapping("/getConfigFromNacos")
    public R getConfigFromNacos(){
        String className = myNacosConfig.getClassName();
        System.out.println("className:"+className);
        return R.OK(className);
    }

    /**
     * 从nacos配置中心读取配置数据,但是不适用配置类
     * @return
     */
    @PostMapping("/getConfigFromNacos2")
    public R getConfigFromNacos2(){
        System.out.println("className："+className);
        return R.OK(className);
    }

    /**
     * FastDFS文件上传
     * @return
     */
    @PostMapping("/uploadImage")
    public R uploadImage(@RequestPart("file") MultipartFile file){
        return tbUserService.uploadImage(file);
    }

    /**
     * 根据用户id获取角色列表
     * @param userId
     * @return
     */
    @PostMapping("/getUserRole/{userId}")
    public R getUserRole(@PathVariable(name = "userId") Integer userId){
        return tbUserService.getUserRole(userId);
    }

    /**
     * 审核用户
     * @param tbUser
     * @return
     */
    @PostMapping("/checkUser")
    public R checkUser(@RequestBody TbUser tbUser){
        return tbUserService.checkUser(tbUser);
    }

    /**
     * 删除单个商户
     * @param userId
     * @return
     */
    @PostMapping("/deleteUserById/{userId}")
    public R deleteUserById(@PathVariable("userId") Integer userId){
        return tbUserService.deleteUserById(userId);
    }

    /**
     * 批量删除商户
     * @param userList
     * @return
     */
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<TbUser> userList){
        return tbUserService.deleteBatch(userList);
    }
}
